﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.UI;

namespace Kaskelot.SP.UI.CONTROLTEMPLATES.Kaskelot.SP.UI.Forms
{
    public abstract class BaseForm : UserControl
    {
        protected string GetSelected(object item, string itemField, int sourceValue)
        {
            Type typeofitem = item.GetType();
            PropertyInfo prop = typeofitem.GetProperty(itemField);
            object value = prop.GetValue(item, null);
            if (value == null)
                return string.Empty;

            if (int.Parse(value.ToString()) == sourceValue)
                return " selected='selected'";
            else
                return string.Empty;
        }

        protected string GetSelected(object item, string itemField, object currentItems)
        {
            if (currentItems == null)
                return string.Empty;

            Type typeofitem = item.GetType();
            PropertyInfo prop = typeofitem.GetProperty(itemField);
            object value = prop.GetValue(item, null);
            if (value == null)
                return string.Empty;

            IEnumerable list = (IEnumerable)currentItems;
            foreach (var currItem in list)
            {
                var currValue = prop.GetValue(currItem, null);
                if (int.Parse(currValue.ToString()) == int.Parse(value.ToString()))
                    return " selected='selected'";
            }
            return string.Empty;
        }

        protected string GetSelected(object value, string sourceValue)
        {
            if (value != null && value.ToString() == sourceValue)
                return " selected='selected'";
            else
                return string.Empty;
        }

        protected string GetChecked(object item, string field)
        {
            Type typeofitem = item.GetType();
            PropertyInfo prop = typeofitem.GetProperty(field);
            object value = prop.GetValue(item, null);
            if (value == null)
                return string.Empty;

            bool isTrue = false;
            if (value is bool)
                isTrue = (bool)value;
            else if (value is bool?)
                isTrue = ((bool?)value).HasValue ? ((bool?)value).Value : false;

            return isTrue ? "checked='checked'" : string.Empty;
        }
    }
}
